package admin

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"test_api/controllers"
	"test_api/modules"
)

type UserController struct {
}

// GetUserInfo 获取用户信息
func (u UserController) GetUserInfo(c *gin.Context) {
	id := c.Query("id")
	// id 转成 int
	idInt, err := strconv.Atoi(id)
	if err != nil {
		controllers.ReturnError(c, 400, "参数错误，id必须为数字")
		return
	}
	userModel := modules.UserModel{}
	res, err := userModel.GetUserInfo(idInt)
	if err != nil {
		controllers.ReturnError(c, 500, "获取用户信息失败")
		return
	}
	controllers.ReturnSuccess(c, 200, "获取成功", res)
}

// AddUser 添加用户
func (u UserController) AddUser(c *gin.Context) {
	username := c.Query("username")
	nickname := c.Query("nickname")
	req := modules.CreateUserRequest{
		Username: username,
		Nickname: nickname,
	}

	userModel := modules.UserModel{}
	res, err := userModel.AddUser(req)
	if err != nil {
		controllers.ReturnError(c, 500, "添加用户失败")
		return
	}
	controllers.ReturnSuccess(c, 200, "添加用户成功", res)
}

func (u UserController) UpdateUser(c *gin.Context) {
	id := c.Query("id")
	idInt, err := strconv.Atoi(id)
	if err != nil {
		controllers.ReturnError(c, 400, "参数错误")
		return
	}
	username := c.Query("username")
	nickname := c.Query("nickname")
	req := modules.UpdateUserRequest{
		Username: username,
		Nickname: nickname,
	}
	userModel := modules.UserModel{}
	res, err := userModel.UpdateUser(idInt, req)
	if err != nil {
		controllers.ReturnError(c, 500, "修改用户失败")
		return
	}
	controllers.ReturnSuccess(c, 200, "修改用户成功", res)

}
